import React, { useState, useEffect } from 'react';
import styles from '../lyf/WebSoket.module.css';
import { LeftOutline } from 'antd-mobile-icons';
import { useNavigate,useLocation } from 'react-router-dom';
import axios from 'axios';

export default function WebSoket() {
    const navigate = useNavigate();
    const location = useLocation();
    const [input, setInput] = useState('');
    const [messages, setMessages] = useState([]);
    const [isLoading, setIsLoading] = useState(false);
    const [conversationId, setConversationId] = useState('');
    const [audioUrl, setAudioUrl] = useState(null);

    // 从URL参数获取对话ID
    useEffect(() => {
        const params = new URLSearchParams(location.search);
        const id = params.get('conversationId');
        setConversationId(id || 'default');
    }, [location]);

    // 处理接收到的音频数据
    useEffect(() => {
        if (location.state?.audioUrl) {
            setAudioUrl(location.state.audioUrl);
            
            // 添加语音消息到聊天记录
            const voiceMessage = {
                role: 'user',
                content: '[语音消息]',
                time: new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }),
                isVoiceMessage: true,
                audioUrl: location.state.audioUrl
            };
            
            setMessages(prev => [...prev, voiceMessage]);
            
            // 自动发送语音消息的标记到后端
            sendVoiceMessage();
        }
    }, [location.state]);

    // 发送语音消息标记到后端
    const sendVoiceMessage = async () => {
        setIsLoading(true);
        
        try {
            const res = await axios.post('http://localhost:3000/chat', { 
                message: '[语音消息]',
                isVoiceMessage: true
            });
            
            const replyText = res.data.reply;
            
            // 添加AI回复
            setMessages(prev => [...prev, {
                role: 'assistant',
                content: replyText,
                time: new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })
            }]);
        } catch (err) {
            setMessages(prev => [...prev, {
                role: 'assistant',
                content: 'AI服务异常，请稍后再试。',
                time: new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })
            }]);
        } finally {
            setIsLoading(false);
        }
    };

    // 初始化时从localStorage加载聊天记录
    useEffect(() => {
        const loadMessages = () => {
            try {
                const savedConversations = localStorage.getItem('chatConversations');
                const allConversations = savedConversations ? JSON.parse(savedConversations) : {};
                
                if (allConversations[conversationId]) {
                    setMessages(allConversations[conversationId]);
                } else {
                    setMessages([{
                        role: 'assistant',
                        content: '你好！我是弗洛伊德博士AI，有什么可以帮你的吗？',
                        time: new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })
                    }]);
                }
            } catch (err) {
                console.error('加载聊天记录失败:', err);
                setMessages([{
                    role: 'assistant',
                    content: '你好！我是弗洛伊德博士AI，有什么可以帮你的吗？',
                    time: new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })
                }]);
            }
        };
        loadMessages();
    }, [conversationId]);

    // 保存聊天记录
    useEffect(() => {
        if (messages.length > 0) {
            const savedConversations = localStorage.getItem('chatConversations');
            const allConversations = savedConversations ? JSON.parse(savedConversations) : {};
            
            allConversations[conversationId] = messages;
            localStorage.setItem('chatConversations', JSON.stringify(allConversations));
        }
    }, [messages, conversationId]);

    const sendMessage = async () => {
      if (!input.trim() || isLoading) return;
      
      // 添加用户消息
      const userMessage = {
          role: 'user',
          content: input,
          time: new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })
      };
      
      setMessages(prev => [...prev, userMessage]);
      setInput('');
      setIsLoading(true);
      
      // 添加AI加载中的消息
      const loadingMessage = {
          role: 'assistant',
          content: '',
          time: new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }),
          isLoading: true
      };
      setMessages(prev => [...prev, loadingMessage]);
      
      try {
          const res = await axios.post('http://localhost:3000/chat', { message: input });
          const replyText = res.data.reply;
          
          // 移除加载中的消息
          setMessages(prev => {
              const newMessages = [...prev];
              newMessages.pop();
              return newMessages;
          });
          
          // 逐字添加消息
          let displayedText = '';
          for (let i = 0; i < replyText.length; i++) {
              await new Promise(resolve => setTimeout(resolve, 50)); // 50ms间隔
              displayedText += replyText[i];
              
              setMessages(prev => {
                  const newMessages = [...prev];
                  const lastIndex = newMessages.length - 1;
                  
                  if (lastIndex >= 0 && newMessages[lastIndex].role === 'assistant') {
                      // 更新现有消息
                      newMessages[lastIndex] = {
                          ...newMessages[lastIndex],
                          content: displayedText
                      };
                  } else {
                      // 添加新消息
                      newMessages.push({
                          role: 'assistant',
                          content: displayedText,
                          time: new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })
                      });
                  }
                  
                  return newMessages;
              });
          }
        } catch (err) {
            setMessages(prev => {
                const newMessages = [...prev];
                newMessages.pop(); // 移除加载中消息
                return [...newMessages, {
                    role: 'assistant',
                    content: 'AI服务异常，请稍后再试。',
                    time: new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })
                }];
            });
        } finally {
            setIsLoading(false);
        }
    };

    return (
        <div className={styles.container}>
            {/* 顶部信息栏 */}
            <div className={styles.header}>
                <div className={styles.backto} onClick={() => navigate('/newtalk')}>
                    <LeftOutline className={styles.back} />
                </div>
                <h1 className={styles.title}>AI弗洛伊德博士</h1>
                <div className={styles.info}>
                    <span className={styles.version}>GPT-6</span>
                </div>
            </div>
            
            {/* 主要内容区域 */}
            <div className={styles.mainContent}>
                <div className={styles.messageContainer}>
                    {messages.map((msg, idx) => (
                        <div 
                            key={idx} 
                            className={`${styles.messageBubble} ${
                                msg.role === 'user' ? styles.userBubble : styles.aiBubble
                            } ${msg.isLoading ? styles.loadingBubble : ''}`}
                        >
                            <div>
                                {msg.isVoiceMessage ? (
                                    <div className={styles.voiceMessage}>
                                        <span>🎤 语音消息</span>
                                        <audio 
                                            src={msg.audioUrl} 
                                            controls
                                            className={styles.voicePlayer}
                                        />
                                    </div>
                                ) : msg.isLoading ? (
                                    <div className={styles.loadingDots}>
                                        <span>.</span>
                                        <span>.</span>
                                        <span>.</span>
                                    </div>
                                ) : (
                                    msg.content
                                )}
                            </div>
                        </div>
                    ))}
                </div>
            </div>
            
            {/* 底部输入区域 */}
            <div className={styles.inputArea}>
                <div className={styles.inputContainer}>
                    <button 
                        className={styles.iconButton} 
                        onClick={() => navigate('/luyin')}
                    >
                        <span className={styles.voiceIcon}>🎤</span>
                    </button>
                    <input 
                        type="text" 
                        className={styles.messageInput}
                        placeholder="输入消息..."
                        value={input}
                        onChange={e => setInput(e.target.value)}
                        onKeyDown={e => e.key === 'Enter' && sendMessage()}
                        disabled={isLoading}
                    />
                    <div className={styles.icons}>
                        <button className={styles.iconButton}>
                            <span className={styles.cameraIcon}>📷</span>
                        </button>
                        <button 
                            className={styles.sendButton} 
                            onClick={() => sendMessage()}
                            disabled={isLoading || !input.trim()}
                        >
                            <span className={styles.sendIcon}>
                                {isLoading ? '发送中...' : '发送'}
                            </span>
                        </button>
                    </div>
                </div>
            </div>
        </div>
    );
}